package com.wj.wjpicture.infrastructure.config;

import org.springframework.amqp.core.*;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class RabbitMqConfig {
    // 交换机名称（处理图片任务的主题交换机）
    public static final String PICTURE_EXCHANGE = "picture.process.exchange";

    // 队列名称（分别对应两种任务）
    public static final String THUMBNAIL_QUEUE = "picture.thumbnail.queue"; // 缩略图生成队列
    public static final String FORMAT_CONVERT_QUEUE = "picture.format.queue"; // 格式转换队列

    // 路由键（用于区分任务类型）
    public static final String THUMBNAIL_ROUTING_KEY = "task.thumbnail";
    public static final String FORMAT_CONVERT_ROUTING_KEY = "task.format";

    /**
     * 声明主题交换机（支持按路由键灵活路由）
     */
    @Bean
    public TopicExchange pictureExchange() {
        // durable=true：交换机持久化（服务重启后不丢失）
        return ExchangeBuilder.topicExchange(PICTURE_EXCHANGE).durable(true).build();
    }

    /**
     * 声明缩略图生成队列
     */
    @Bean
    public Queue thumbnailQueue() {
        return QueueBuilder.durable(THUMBNAIL_QUEUE)
                .withArgument("x-dead-letter-exchange", "") // 死信交换机（可选）
                .withArgument("x-dead-letter-routing-key", "picture.dlq.queue") // 死信队列
                .build();
    }

    /**
     * 声明格式转换队列
     */
    @Bean
    public Queue formatConvertQueue() {
        return QueueBuilder.durable(FORMAT_CONVERT_QUEUE).build();
    }

    /**
     * 绑定缩略图队列到交换机
     */
    @Bean
    public Binding thumbnailBinding(Queue thumbnailQueue, TopicExchange pictureExchange) {
        return BindingBuilder.bind(thumbnailQueue)
                .to(pictureExchange)
                .with(THUMBNAIL_ROUTING_KEY); // 精确匹配路由键
    }

    /**
     * 绑定格式转换队列到交换机
     */
    @Bean
    public Binding formatConvertBinding(Queue formatConvertQueue, TopicExchange pictureExchange) {
        return BindingBuilder.bind(formatConvertQueue)
                .to(pictureExchange)
                .with(FORMAT_CONVERT_ROUTING_KEY);
    }
}